package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.SmsSkuboundsFeign;
import com.atguigu.gmall.pms.service.*;
import com.atguigu.gmall.pms.vo.spu.SpuAttrValueVo;
import com.atguigu.gmall.pms.vo.spu.SpuInfoVo;
import com.atguigu.gmall.pms.vo.spu.SpuSkusAttr;
import com.atguigu.gmall.sms.vo.SkuSaleVo;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.SpuMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuService")
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Autowired
    SpuDescService spuDescService;
    @Autowired
    SpuAttrValueService spuAttrValueService;
    @Autowired
    SkuService skuService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuAttrValueService skuAttrValueService;
    @Autowired
    SmsSkuboundsFeign skuboundsFeign;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    /**
     * 根据分类id查询spu信息
     * @param id
     * @param pageParamVo
     * @return
     */
    @Override
    public PageResultVo querySpuList(Long id, PageParamVo pageParamVo) {

        QueryWrapper<SpuEntity> wrapper = new QueryWrapper<>();

        if (id!=null){
            wrapper.eq("category_id",id);
        }

        String key = pageParamVo.getKey();
        if (StringUtils.isNotBlank(key)){
            wrapper.and(t->{
                t.eq("id",key).or().like("name",key);
            });
        }

        IPage<SpuEntity> page = this.page(
                pageParamVo.getPage(),
                wrapper
        );

        return new PageResultVo(page);
    }

    /*
    发布商品
     */
    @GlobalTransactional
    @Override
    public void PublishSpu(SpuInfoVo spu) {
        //保存spu信息

        this.save(spu);
        //保存spu图片信息
        SpuDescEntity spuDescEntity = new SpuDescEntity();
        List<String> spuImages = spu.getSpuImages();
        if (!CollectionUtils.isEmpty(spuImages)){
            spuDescEntity.setSpuId(spu.getId());
            spuDescEntity.setDecript(StringUtils.join(spuImages,","));
            spuDescService.save(spuDescEntity);
        }
        //保存spu基本属性信息
        List<SpuAttrValueVo> baseAttrs = spu.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrs)){
            List<SpuAttrValueEntity> collect = baseAttrs.stream().map(item -> {
                SpuAttrValueEntity valueEntity = new SpuAttrValueEntity();
                BeanUtils.copyProperties(item, valueEntity);
                valueEntity.setSpuId(spu.getId());
                return valueEntity;
            }).collect(Collectors.toList());
            spuAttrValueService.saveBatch(collect);
        }

        List<SpuSkusAttr> skus = spu.getSkus();
        if (CollectionUtils.isEmpty(skus)){
            return;
        }
        //保存sku信息
        skus.forEach(item->{
            //保存sku基本信息
            SkuEntity skuEntity = new SkuEntity();
            List<String> images = item.getImages();
            BeanUtils.copyProperties(item,skuEntity);
            skuEntity.setCategoryId(spu.getCategoryId());
            skuEntity.setBrandId(spu.getBrandId());
            skuEntity.setSpuId(spu.getId());
            if (!CollectionUtils.isEmpty(images)){
                skuEntity.setDefaultImage(StringUtils.isBlank(item.getDefaultImage())?images.get(0): item.getDefaultImage());
            }
            skuService.save(skuEntity);
            //保存sku图片信息 一张图片对于一行
            if (!CollectionUtils.isEmpty(images)){
                List<SkuImagesEntity> imagesEntities = images.stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuEntity.getId());
                    skuImagesEntity.setUrl(image);
                    skuImagesEntity.setDefaultStatus(StringUtils.equals(skuEntity.getDefaultImage(), image) ? 1 : 0);
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);
            }
            //保存sku销售属性参数
            List<SkuAttrValueEntity> saleAttrs = item.getSaleAttrs();
            saleAttrs.forEach(attr -> {
                attr.setSkuId(skuEntity.getId());

            });
            skuAttrValueService.saveBatch(saleAttrs);
            //保存sku满减信息
            SkuSaleVo skuSaleVo = new SkuSaleVo();
            BeanUtils.copyProperties(item,skuSaleVo);
            skuSaleVo.setSkuId(skuEntity.getId());
            skuboundsFeign.saveSkuSales(skuSaleVo);
        });

        //发送消息 给search服务 保存更新商品信息
        this.rabbitTemplate.convertAndSend("PMS_SPU_EXCHANGE", "item.insert", spu.getId());

        //int i = 1/0;
        //
    }

}